import React, {PureComponent, useEffect, useState} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Keyboard,
  Modal,
  Linking,
  DeviceEventEmitter,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {LinearBoardButton, TextButton} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {updateUserInfo, setCurrentChainId} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import LinearGradient from 'react-native-linear-gradient';
import {Colors} from '../../styles/common';
import StorageManager, {METAMASK_ADDRESS} from '../../storage';
import {bindWallet} from '../../api/user';
import {useWalletConnect} from '@walletconnect/react-native-dapp';

function WalletCompontent({
  navigation,
  showSelectChain,
  registAddress,
  chainInfo,
  closeConnect,
}) {
  const connector = useWalletConnect();
  console.log('++++');
  console.log(connector);

  let [localAddress, setLocalAddress] = useState();

  useEffect(() => {
    let listener = DeviceEventEmitter.addListener('updateChain', killSession);

    let connectListener = DeviceEventEmitter.addListener(
      'showConnect',
      connectWallet,
    );

    StorageManager.load(METAMASK_ADDRESS).then((data) => {
      console.log('----------', data);
      if (data) {
        setLocalAddress(JSON.parse(data).address);
      }
    });

    if (connector.connected == false) {
      setTimeout(() => {
        connectWallet();
      }, 500);
    }

    return () => {
      listener.remove();
      connectListener.remove();
    };
  }, []);

  const chainIdList = {
    1: 'ETH Mainnet',
    3: 'Ropsten',
    4: 'Rinkeby',
    56: 'BSC Mainnet',
    97: 'BSC Testnet',
    137: 'Polygon Mainnet',
  };

  const connectWallet = async () => {
    if (connector.connected) {
      return;
    }
    try {
      console.log('开始连接');
      let res = await connector.connect();
      console.log('连接成功' + JSON.stringify(res));
      // this.onConnect(payload);
      const {peerId, chainId, accounts} = res;
      if (!peerId) {
        return;
      }

      setLocalAddress(accounts[0]);

      showToast('Connection successed');
      registAddress && registAddress(accounts[0]);
    } catch (err) {
      console.log('connect钱包出现错误' + err);
    }
  };

  const updateChain = async () => {
    console.log(this.state.chainInfo);

    connector
      .updateChain(this.state.chainInfo)
      .then((res) => {
        console.log('更新成功' + res);
      })
      .catch((err) => {
        console.log('更新失败' + err);
      });
  };

  const killSession = async (needUpdateChain = false) => {
    console.log(connector);

    await connector
      .killSession()
      .then((res) => {
        console.log('关闭成功' + res);

        setLocalAddress(undefined);

        closeConnect && closeConnect();
      })
      .catch((err) => {
        console.log('关闭失败' + err);
      });
  };

  const copyAddress = () => {
    console.log('复制地址');
    if (connector.connected) {
      Clipboard.setString(connector.accounts[0]);
      showToast('Copied!', undefined, 3000);
    }
  };

  return (
    <View style={{flex: 1, backgroundColor: '#fff'}}>
      <NormalHeader
        navigation={navigation}
        text="Wallet"
        left={{
          icon: require('../../assets/common/common_back_white.png'),
          onPress: () => {
            Keyboard.dismiss();
            navigation.goBack();
          },
        }}
      />
      <View style={{padding: 10, flex: 1, backgroundColor: '#160231'}}>
        <LinearGradient
          start={{x: 0, y: 1}}
          end={{x: 1, y: 1}}
          colors={['#CE18EC', '#6601F5']}
          style={{
            flex: 1,
            borderTopLeftRadius: 20,
            borderTopRightRadius: 20,
            padding: 2,
            marginBottom: -20,
          }}>
          <View
            style={{
              flex: 1,
              backgroundColor: 'white',
              borderTopLeftRadius: 20 - 2,
              borderTopRightRadius: 20 - 2,
              alignItems: 'center',
            }}>
            <View
              style={{
                width: '100%',
                paddingLeft: 10,
                paddingRight: 10,
                paddingTop: 10,
                flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}>
              <View style={{flexDirection: 'row'}}>
                <View
                  style={{
                    width: 16,
                    height: 16,
                    borderRadius: 8,
                    backgroundColor: connector.connected
                      ? '#00ff00'
                      : '#ff0000',
                    marginRight: 5,
                  }}></View>
                <Text style={{color: Colors.fontBlackColor_0a}}>
                  {connector.connected ? 'Connected' : 'Disconnected'}
                </Text>
              </View>
              {connector.connected ? (
                <Text style={{color: Colors.fontBlackColor_0a}}>
                  {'Network:' +
                    (chainIdList[connector.chainId]
                      ? chainIdList[connector.chainId]
                      : 'unknow chain')}
                </Text>
              ) : null}
            </View>
            <Image
              source={require('../../assets/user/wallet.png')}
              style={{marginTop: 100}}></Image>
            <TouchableOpacity onPress={copyAddress}>
              <Text
                style={{
                  // fontWeight: 'bold',
                  fontSize: 16,
                  color: Colors.fontBlackColor_0a,
                  // color: Colors.fontPurpleColorDark,
                  //   marginTop: 16,
                  textAlign: 'center',
                  margin: 30,
                  marginBottom: 50,
                }}>
                {localAddress ? localAddress : 'Connect to wallet'}
              </Text>
            </TouchableOpacity>
            {/* <Text
              style={{
                //   marginTop: 16,
                fontSize: 12,
                color: Colors.fontGrayColor_a0,
                marginLeft: 50,
                marginRight: 50,
                marginBottom: 50,
              }}>
              Your crypto wallet securely stores your digtial goods and
              cryptocurrencies
            </Text> */}
            {connector.connected ? (
              <LinearBoardButton
                buttonStyle={{
                  width: 200,
                  height: 40,
                }}
                onPress={killSession}
                text={'Logout'}></LinearBoardButton>
            ) : (
              <LinearBoardButton
                buttonStyle={{
                  width: 200,
                  height: 40,
                }}
                onPress={connectWallet}
                text={'Switch Wallet'}></LinearBoardButton>
            )}
            {/* <TouchableOpacity
              style={{width: '100%', height: 150, flexDirection: 'row'}}
              onPress={connectWallet}>
              <LinearGradient
                start={{x: 0, y: 1}}
                end={{x: 1, y: 1}}
                colors={['#CE18EC', '#6601F5']}
                style={{
                  marginTop: 60,
                  flex: 1,
                  marginLeft: 20,
                  marginRight: 20,
                  height: '100%',
                  borderRadius: 20,
                  padding: 2,
                  textAlign: 'center',
                }}>
                <View
                  style={{
                    backgroundColor: Colors.themeColor,
                    flex: 1,
                    borderRadius: 20 - 2,
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}>
                  <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <Image
                      style={{width: 50, height: 30}}
                      source={require('../../assets/user/walletconnect_logo.png')}
                    />
                    <Text
                      style={{
                        marginLeft: 20,
                        fontWeight: 'bold',
                        color: Colors.fontPurpleColorLight,
                        fontSize: 20,
                      }}>
                      WALLET CONNECT
                    </Text>
                  </View>
                  <Text
                    style={{
                      marginTop: 16,
                      fontSize: 12,
                      color: Colors.fontGrayColor_a0,
                      marginLeft: 30,
                      marginRight: 30,
                      textAlign: 'center',
                    }}>
                    Popular crypto wallets that are secure and extremely
                    flexible.
                  </Text>
                </View>
              </LinearGradient>
            </TouchableOpacity> */}
          </View>
        </LinearGradient>
      </View>
    </View>
  );
}

class Auction extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      chainInfo: {
        chainId: props.chainConfig.chainId,
        networkId: props.chainConfig.chainId,
        rpcUrl: props.chainConfig.url,
        nativeCurrency: {
          name: props.chainConfig.name,
          symbol: 'BNB',
        },
      },
    };
  }

  componentDidMount() {
    //App 激活状态下进行的跳转
    this.linkingListen = Linking.addEventListener('url', (event) => {
      this.handleOpenURL(event.url);
    });
  }

  handleOpenURL = async (url) => {
    console.log('---跳转的url为' + url);
    try {
      let paramsPart = url.split('?')[1];
      let params = paramsPart.split('&') || [];
      let param = {};
      params.map((item) => {
        let key = item.split('=')[0];
        let value = item.split('=')[1];
        param[key] = value;
      });
      console.log(param);
      if (param?.address) {
        DeviceEventEmitter.emit('showConnect');
      }
    } catch (err) {
      //   this._showAlert(err);
    }
  };

  registAddress = async (address) => {
    console.log(address);
    console.log(this.props.userInfo.token);

    bindWallet({
      address,
      userToken: this.props.userInfo.token,
    }).then((res) => {
      console.log('绑定钱包地址成功');
    });

    // let result = await registAddress({address});
    StorageManager.save(
      METAMASK_ADDRESS,
      JSON.stringify({
        address: address,
        // token: result.data.token,
        hiddenAlert: false,
      }),
    );
    this.props.updateUserInfo({
      ...this.props.userInfo,
      metamaskAddress: address,
      // metamaskToken: result.data.token,
    });
  };

  componentWillUnmount() {
    if (this.linkingListen) {
      this.linkingListen.remove();
    }
  }

  showSelectChain = (call) => {
    console.log('提示用户');

    this._showAlert({
      content: 'Not support this chain ,please add bsc chain',
      okTitle: 'Go',
      alertOkPress: () => {
        call && call();
        Linking.openURL(
          'https://metamask.app.link/dapp/metamask.signin.art/testnet.html',
        );
      },
    });
  };

  closeConnect = () => {
    // console.log('====================================');
    console.log('清除连接数据');
    // console.log('====================================');
    StorageManager.remove(METAMASK_ADDRESS);
    this.props.updateUserInfo({
      ...this.props.userInfo,
      metamaskAddress: null,
      // metamaskToken: null,
    });
  };

  renderComponent = () => {
    return (
      <WalletCompontent
        navigation={this.props.navigation}
        // showSelectChain={this.showSelectChain}
        registAddress={this.registAddress}
        chainInfo={this.state.chainInfo}
        closeConnect={this.closeConnect}
      />
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  chainConfig: state.Chain.config,
  currentChainId: state.Chain.currentChainId,
});

const mapDispatchToProps = (dispatch) => ({
  updateUserInfo: (item) => dispatch(updateUserInfo(item)),
  setCurrentChainId: (item) => dispatch(setCurrentChainId(item)),
});

export default connect(mapStateToProps, mapDispatchToProps)(Auction);
